package com.ideal.manage.esms.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ideal.manage.esms.bean.project.StadningBookInfo;
import com.ideal.manage.esms.bean.project.AccountProperty;
import com.ideal.manage.esms.bean.project.EquipmentManage;
import com.ideal.manage.esms.bean.project.ProjectManage;
import com.ideal.manage.esms.repository.diagnostic.StadningBookInfoRepository;
import com.ideal.manage.esms.repository.project.AccountPropertyRepository;
import com.ideal.manage.esms.repository.project.EquipmentManageRepository;
import com.ideal.manage.esms.repository.project.ProjectManageRepository;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created By Dai On 2018/5/18
 * Remark: 系统监控-台账信息存储表 Service
 */
@Service
public class StadningBookInfoService {
    private Logger logger = LoggerFactory.getLogger(StadningBookInfoService.class);

    @Autowired
    private StadningBookInfoRepository stadningBookInfoRepository;
    @Autowired
    private EquipmentManageRepository equipmentManageRepository;
    @Autowired
    private AccountPropertyRepository accountPropertyRepository;
    @Autowired
    private ProjectManageRepository projectManageRepository;

    @Value("${uploadFile.path}")
    private String path;

    /**
     * 保存台账信息
     *
     * @param uploadFile
     * @param file_id
     * @param data
     */
    public String save(MultipartFile uploadFile, String file_id, String data, String id) {
        List<StadningBookInfo> deleteList = new ArrayList<>();
        ProjectManage projectManage = null;
        // 1. 找到设备
        EquipmentManage equipmentManage = equipmentManageRepository.findOne(id);

        if (equipmentManage != null) {
            // 2. 找到所有已有的值(要删除的)
            deleteList = stadningBookInfoRepository.findByEquipmentManage(equipmentManage);
        } else {
            projectManage = projectManageRepository.findOne(id);
            // 2. 找到所有已有的值(要删除的)
            deleteList = stadningBookInfoRepository.findByProjectManage(projectManage);
        }

        // 3. 要保存的list
        List<StadningBookInfo> list = new ArrayList<>();
        // 4. 保存进去
        JSONArray jsonArray = JSONArray.parseArray(data);
        for (int i = 0, j = jsonArray.size(); i < j; i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            String account_id = jsonObject.getString("id");
            String value = jsonObject.getString("value");
            boolean flag = true;
            // 已有的放进去就是了
            for (StadningBookInfo s : deleteList) {
                if (s.getAccount().getId().equals(account_id)) {
                    s.setVal(value);
                    list.add(s);
                    deleteList.remove(s);
                    flag = false;
                    break;
                }
            }
            // 没有的就新建
            if (flag) {
                StadningBookInfo stadningBookInfo = new StadningBookInfo();
                stadningBookInfo.setVal(value);
                AccountProperty accountProperty = accountPropertyRepository.findOne(account_id);
                stadningBookInfo.setAccount(accountProperty);
                if (equipmentManage != null) {
                    stadningBookInfo.setEquipment(equipmentManage);
                } else {
                    stadningBookInfo.setProject(projectManage);
                }
                stadningBookInfo.setCreateTime(new Date());
                list.add(stadningBookInfo);
            }
        }
        // 2. 如果有文件的话
        if (StringUtils.isNotBlank(file_id)) {
            String name = uploadFile.getOriginalFilename();
            name = file_id + name.substring(name.lastIndexOf("."));
            File dir = new File(path);
            if (!dir.exists()){
                dir.mkdirs();
            }
            File file = new File(path + File.separator + name);
            if (file.exists()) {
                file.delete();
            }
            try {
                uploadFile.transferTo(file);
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println(file.getPath());
            StadningBookInfo stadningBookInfo = new StadningBookInfo();
            stadningBookInfo.setVal(file.getPath());
            AccountProperty accountProperty = accountPropertyRepository.findOne(file_id);
            stadningBookInfo.setAccount(accountProperty);
            if (equipmentManage != null) {
                stadningBookInfo.setEquipment(equipmentManage);
            } else {
                stadningBookInfo.setProject(projectManage);
            }
            stadningBookInfo.setCreateTime(new Date());
            list.add(stadningBookInfo);
        }
        deleteList.forEach(stadningBookInfo -> stadningBookInfo.setIsValid(0));
        stadningBookInfoRepository.save(deleteList);
        stadningBookInfoRepository.save(list);
        return "保存成功";
    }
}
